package com.example.controller;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.bean.Books;
import com.example.bean.Borrow;
import com.example.bean.Return;
import com.example.bean.User;
import com.example.exception.ServiceException;
import com.example.mapper.BooksMapper;
import com.example.service.BorrowService;
import com.example.service.ReturnService;
import com.example.service.UserService;
import com.example.until.Result;
import com.example.until.ResultCodeEnum;
import com.example.until.TokenUtils;
import com.example.until.UserDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @title: Course
 * @Author wjf
 * @Date: 2022/9/29 14:34
 * @Version 1.0
 */
@RestController
@CrossOrigin
@Slf4j
@RequestMapping("/borrow")
public class BorrowController {

    @Autowired
    private BorrowService borrowService;

    @Resource
    private BooksMapper booksMapper;

    @Resource
    private UserService userService;

    @Autowired
    private ReturnService returnService;

    /**
     * 获取借阅人 下拉框数据
     * @return
     */
    @GetMapping("/getUserOptions")
    public Result getUserOptions() {
        List<Borrow> list = borrowService.list();
        List<Integer> collect = list.stream().distinct().map(m -> m.getUserId()).collect(Collectors.toList());
        List<User> collect1 = userService.listByIds(collect).stream().map(m -> {
            m.getNickname();
            m.getId();
            return m;
        }).collect(Collectors.toList());
        return Result.ok(collect1);
    }

    @GetMapping("/page")
    public Result<IPage<Borrow>> getAllUser(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "5") Integer pageSize,
            @RequestParam(defaultValue = "") String bookName,
            @RequestParam(value = "nickName", defaultValue = "") String userName) {
        IPage<Borrow> page = new Page<>(current, pageSize);
        System.out.println(bookName);
        System.out.println(userName);
        User user = TokenUtils.getCurrentUser();
        Integer id = null;
        if ("学生".equals(user.getRole())) {
            id = user.getId();
        }
        IPage<Borrow> page1 = borrowService.findPage(page, id, bookName, userName);
//          page1.getRecords().stream().map(m -> m.getNickName()).distinct();

        return Result.ok(page1);
    }

    @GetMapping({"/byName/{name}"})
    public Result getUserByName(@PathVariable String name) {
        QueryWrapper<Borrow> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(name), "name", name);
        Borrow one = borrowService.getOne(queryWrapper);
        return Result.ok(one);
    }

    @GetMapping("/{id}")
    public Result<Borrow> getCourseById(@PathVariable("id") Integer id) {
        Borrow course = borrowService.getById(id);
        return Result.ok(course);
    }

    @PostMapping("/save")
    public Result<Boolean> saveUser(@RequestBody Borrow borrow) {
        boolean save = borrowService.save(borrow);
        return Result.ok(save);
    }

    /**
     * 审核   接口
     *
     * @param borrow
     * @return
     */
    @Transactional
    @PutMapping("/update")
    public Result<Boolean> putUser(@RequestBody Borrow borrow) {
        LambdaQueryWrapper<Borrow> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Borrow::getBookId, borrow.getBookId())
                .eq(Borrow::getUserId, borrow.getUserId());
        borrow.setCheckTime(DateUtil.now());
        boolean b = borrowService.update(borrow, queryWrapper);
        if (b) {
            // 审核未通过  books 的库存加一
            if (borrow.getStatus() == 2) {
                Books books = booksMapper.selectById(borrow.getBookId());
                Books books1 = new Books();
                books1.setId(borrow.getBookId());
                books1.setNum(books.getNum() + 1);
                booksMapper.updateById(books1);
            }
            return Result.ok();
        }
        return Result.fail();
    }

    @Transactional
    @DeleteMapping("/delete/{id}/{type}")
    public Result<Boolean> deleteUser(@PathVariable("id") Integer bookId,@PathVariable Integer type) {
        Integer userId = TokenUtils.getCurrentUser().getId();
        LambdaQueryWrapper<Borrow> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Borrow::getBookId, bookId)
                .eq(Borrow::getUserId, userId);
        try {
            if (type==2){  //归还
                // 归还书籍存入数据到 return表
                Borrow one = borrowService.getOne(queryWrapper);
                Return re = new Return();
                System.out.println(one);
                re.setUserId(one.getUserId());
                re.setBookId(one.getBookId());
                re.setBorrowTime(one.getBorrowTime());
                re.setReturnTime(DateUtil.now());
                re.setBorrowId(one.getBorrowId()); //设置借阅号
                boolean save = returnService.save(re);
            }
            if (type==3){  //用户取消借阅申请 书库存加1
                Books books = new Books();
                Books books1 = booksMapper.selectById(bookId);
                books.setNum(books1.getNum() + 1);
                books.setId(books1.getId());
                booksMapper.updateById(books);
            }
            boolean b = borrowService.remove(queryWrapper);  //删除记录
            if (b){
                return Result.ok();
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new ServiceException(ResultCodeEnum.SERVICE_ERROR);
        }


//            Books books = new Books();
//            Books books1 = booksMapper.selectById(bookId);
//            books.setNum(books1.getNum() + 1);
//            books.setId(books1.getId());
//            int i = booksMapper.updateById(books);
//            if (i==1){
//                LambdaQueryWrapper<Borrow> queryWrapper1 = new LambdaQueryWrapper<>();
//                queryWrapper1.eq(Borrow::getBookId, bookId)
//                        .eq(Borrow::getUserId, userId);
//                Borrow borrow = new Borrow();
//                borrow.setReturnTime(DateUtil.now());
//                boolean update = borrowService.update(borrow, queryWrapper1);
//                if (update){
//                    return Result.ok();
//                }
//                return Result.fail();
//            }
            return Result.fail();
    }

    @DeleteMapping("/delete/batch/{ids}")
    public Result<Boolean> deleteMoreUser(@PathVariable List<Integer> ids) {
        boolean b = borrowService.removeByIds(ids);
        return Result.ok(b);
    }

}
